<?php
class publication_model extends CI_Model{
	
	function __construct(){
		parent::__construct();
		$this->load->database();
	}
	
	/**
	 * Inserta a la bd una serie nueva con los parametros que llegen
	 */
	public function getPublications($params){
		$this->load->model('series_model');
		$this->load->model('films_model');
		
		$params['list'] = isset($params['list'])? $params['list']: 'all';
		
		$genre_film		= 'WHERE p.prox_estreno = 0';
		$genre_serie	= '';
		$order_film 	= 'p.fecha';
		$order_serie 	= 'sc.fecha';
		$order_all		= 't.last_update';
		if(isset($params['order_by'])){
			if($params['order_by'] == 'title'){
				$order_film 	= 'p.titulo';
				$order_serie 	= 'sst.title, sc.titulo';
				$order_all		= "Concat(t.title, ' ', t.title_episode)";
			}
		}
		
		$params['order_as'] = isset($params['order_as'])? $params['order_as']: 'DESC';
		
		if(isset($params['actor']{0})){
			$genre_film		= '
						INNER JOIN peliculas_reparto AS pr ON p.id_pelicula = pr.id_pelicula
					WHERE p.prox_estreno = 0 AND pr.id_actor = '.$params['actor'];
			$genre_serie	= '
						INNER JOIN series_reparto AS sr ON sst.id_serie = sr.id_serie
					WHERE sr.id_actor = '.$params['actor'];
		}elseif(isset($params['genre']{0})){
			$genre_film		= '
						INNER JOIN peliculas_categorias AS pc ON p.id_pelicula = pc.id_pelicula
					WHERE p.prox_estreno = 0 AND pc.id_categoria = '.$params['genre'];
			$genre_serie	= '
						INNER JOIN series_categorias AS scc ON sst.id_serie = scc.id_serie
					WHERE scc.id_categoria = '.$params['genre'];
		}
		
		
		$sql = '';
		switch ($params['list']) {
			case 'all':
			case 'film':
				$sql = "(
					SELECT 
						p.id_pelicula AS id, 
						(SELECT '') AS id_serie,
						p.titulo AS title, 
						p.titulo_limpio AS clean_title, 
						(SELECT '') AS id_season,
						(SELECT '') AS no_season,
						(SELECT '') AS title_episode, 
						(SELECT '') AS clean_title_episode, 
						p.anio AS year, 
						p.idioma AS language, 
						p.subtitulos AS subtitle, 
						p.formato AS format, 
						p.calidad AS quality, 
						p.duracion AS duration, 
						p.tamanio AS size, 
						p.sinopsis_spa AS synopsis_spa, 
						p.sinopsis_eng AS synopsis_eng, 
						p.url_poster_big AS poster_big, 
						p.url_poster_medium AS poster_medium, 
						p.url_poster_small AS poster_small, 
						p.trailer, 
						p.ranking, 
						p.fecha AS last_update, 
						Date(p.fecha_add) AS date,
						u.nombre AS posted_by,
						(SELECT '".lang('txt_type_film')."') AS type
					FROM peliculas AS p 
						INNER JOIN usuarios AS u ON u.id_usuarios = p.id_usuarios
					".$genre_film."
					ORDER BY ".$order_film." ".$params['order_as']."
				)";
				if($params['list'] == 'film')
					break;
			case 'all':
			case 'serie':
				$sql .= $params['list'] == 'all'? ' UNION ': '';
				$sql .= "(
					SELECT 
						sc.id_capitulo AS id,
						sst.id_serie, 
						sst.title, 
						sst.clean_title,
						sst.id_season,
						sst.no_season,
						Concat('".lang('txt_episode')." ', sc.no_capitulo, '".' - '."', sc.titulo) AS title_episode,
						sc.titulo_limpio AS clean_title_episode,
						(SELECT '') AS year, 
						sc.idioma AS language, 
						sc.subtitulos AS subtitle, 
						sc.formato AS format, 
						sc.calidad AS quality, 
						sc.duracion AS duration, 
						sc.tamanio AS size, 
						sc.sinopsis_spa AS synopsis_spa, 
						sc.sinopsis_eng AS synopsis_eng, 
						sst.poster_big, 
						sst.poster_medium, 
						sst.poster_small, 
						sst.trailer, 
						sc.ranking, 
						sc.fecha AS last_update, 
						Date(sc.fecha_add) AS date,
						u.nombre AS posted_by,
						(SELECT 'Serie') AS type
					FROM series_capitulos AS sc
						INNER JOIN(
							SELECT 
								(SELECT id_capitulo FROM series_capitulos WHERE id_temporada = st.id_temporada ORDER BY no_capitulo DESC LIMIT 1) AS id,
								s.id_serie, 
								Concat(s.titulo, ' ".lang('txt_season')." ', st.no_temporada) AS title, 
								s.titulo_limpio AS clean_title,
								st.id_temporada AS id_season,
								st.no_temporada AS no_season, 
								st.url_poster_big AS poster_big, 
								st.url_poster_medium AS poster_medium, 
								st.url_poster_small AS poster_small, 
								st.trailer
							FROM series AS s 
								INNER JOIN series_temporadas AS st ON s.id_serie = st.id_serie 
							WHERE st.prox_estreno = 0
							) AS sst ON sc.id_capitulo = sst.id
						INNER JOIN usuarios AS u ON u.id_usuarios = sc.id_usuario
					".$genre_serie."
					ORDER BY ".$order_serie." ".$params['order_as']."
				)";
			break;
		}
		
		$query = Sys::pagination("
			SELECT 
				t.id, 
				t.id_serie,
				t.title, 
				t.clean_title, 
				t.id_season,
				t.no_season,
				t.title_episode, 
				t.clean_title_episode, 
				t.year, 
				t.language, 
				t.subtitle, 
				t.format, 
				t.quality, 
				t.duration, 
				t.size, 
				t.synopsis_spa, 
				t.synopsis_eng, 
				t.poster_big, 
				t.poster_medium, 
				t.poster_small, 
				t.trailer, 
				t.ranking, 
				Date(t.last_update) AS last_update, 
				Date(t.date) AS date,
				t.posted_by,
				t.type 
			FROM (
				".$sql."
			) AS t
			ORDER BY ".$order_all." ".$params['order_as'], $params, TRUE);
		$response = array(
			'publications' => array(), 
			'total_rows' 		=> $query['total_rows'],
			'items_per_page' 	=> $params['result_items_per_page'],
			'result_page' 		=> $params['result_page']
		);
		
		$res_list = $this->db->query($query['query']);
		foreach ($res_list->result_array() as $value) {
			$value['posters'] = array(
				'big' 		=> $value['poster_big'],
				'medium' 	=> $value['poster_medium'],
				'small' 	=> $value['poster_small']
			);
			
			if($value['type'] == 'Serie'){
				//Si es serie obtenemos las categorias y actores
				$value['categories'] 	= $this->series_model->getCategories($value['id_serie']);
				$value['cast'] 			= $this->series_model->getCast($value['id_serie']);
				$value['sources']		= $this->getServers('series_capitulos_fuentes', 'id_capitulo', $value['id']);
			}else{
				//Si son peliculas obtenemos las categorias y actores
				$value['categories'] 	= $this->films_model->getCategories($value['id']);
				$value['cast'] 			= $this->films_model->getCast($value['id']);
				$value['sources']		= $this->getServers('peliculas_fuentes', 'id_pelicula', $value['id']);
			}

			unset($value['id_serie'], $value['poster_big'], $value['poster_medium'], $value['poster_small']);
			$response['publications'][] = $value;
		}
		
		return $response;
	}

	/**
	 * Obtiene los proximos estrenos
	 */
	public function getComingSoon($params){
		$response = array(
			'films' 	=> array(),
			'series' 	=> array()
		);
		
		//Peliculas
		$res_c = $this->db
			->select('
				id_pelicula AS id, 
				titulo AS title, 
				titulo_limpio AS clean_title, 
				url_poster_medium AS poster')
			->from('peliculas')
			->where('prox_estreno = 1')
		->get();
		foreach ($res_c->result_array() as $value){
			$response['films'][] = $value;
		}
		
		//Series
		$res_c = $this->db
			->select('
				st.id_temporada AS id, 
				s.titulo AS title, 
				s.titulo_limpio AS clean_title, 
				st.no_temporada AS no_season, 
				st.url_poster_medium AS poster')
			->from('series AS s')
				->join('series_temporadas AS st', 's.id_serie = st.id_serie', 'inner')
			->where('st.prox_estreno = 1')
		->get();
		foreach ($res_c->result_array() as $value){
			$response['series'][] = $value;
		}
		
		return $response;
	}
	
	
	
	/**
	 * Obtiene el listado de servidores
	 * @param $table = series_capitulos_fuentes|peliculas_fuentes
	 * @param $field = id_capitulo|id_pelicula
	 * @param $id. value
	 */
	public function getServers($table, $field, $id){
		$res_sourse = $this->db
			->select('
				s.id_servidor AS id, 
				s.nombre AS name, 
				s.url_img, 
				scf.fuente AS short,
				scf.fuente_origen AS origen')
			->from('servidores AS s')
				->join($table.' AS scf', 's.id_servidor = scf.id_servidor', 'inner')
			->where('scf.'.$field.' = '.$id)
			->order_by('s.nombre', 'ASC')
		->get();
		$sources = array();
		foreach ($res_sourse->result_array() as $value) {
			$sources[] = $value;
		}
		
		return $sources;
	}



	public function getInfoActor($params){
		$res_sourse = $this->db
			->select('
				id_actor AS id, 
				nombre AS name')
			->from('actores')
			->where('id_actor = '.$params['actor'])
		->get();
		return $res_sourse->row_array();
	}



	private function exist($table, $sql, $return_res=false){
		$res = $this->db->get_where($table, $sql);
		if($res->num_rows() > 0){
			if($return_res)
				return $res->row();
			return TRUE;
		}
		return FALSE;
	}
}
?>
